import { _decorator, Component, isValid, Node, resources, sp } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('DySpine')
export class DySpine extends sp.Skeleton {

    onLoad(): void {
        super.onLoad();
        
    }
    
    onDestroy(): void {
        super.onDestroy();
        if (this.skeletonData) {
            // 销毁后调用clearTracks()会导致异常
            // this.clearTracks();
            // this.skeletonData = null;
            this.skeletonData.decRef();
        }
    }

    setSpine(path: string ,bundle: string , defualtAnimation: string = null ): void {
        //TODO: 按照资源管理器加载资源
        resources.load(path, sp.SkeletonData,(err, asset) => {
            this.onLoadAsset(asset , defualtAnimation);
        });
    }

    onLoadAsset(value: sp.SkeletonData,anima: string = null): void {
        if (isValid(this.node,true) == false) {
            return;
        }
        if (this.skeletonData) {
            if (this.skeletonData.uuid == value.uuid) {
                return;
            }else{
                this.clearTracks();
                this.skeletonData.decRef();
                this.skeletonData = null;
            }
        }
        this.skeletonData = value;
        this.skeletonData.addRef();
        if (anima) {
            this.animation = anima;
        }
    }
}


